﻿
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #allmap {
            width: 100%;
            height: 500px;
            overflow: hidden;
        }

        #result {
            width: 100%;
            font-size: 12px;
        }

        dl, dt, dd, ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        p {
            font-size: 12px;
        }

        dt {
            font-size: 14px;
            font-family: "微软雅黑";
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding: 5px 0 5px 5px;
            margin: 5px 0;
        }

        dd {
            padding: 5px 0 0 5px;
        }

        li {
            line-height: 28px;
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=nOGwVftGh5UVIpdh9usrVvKs"></script>
    <!--加载鼠标绘制工具-->
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
    <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <!--<script src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>-->
    <script src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils.js"></script>
    <!--[if lt IE 8]>
    <script src="//cdn.lizhanglong.com/js/tools/json2.min.js"></script>
    <![endif]-->
    <title>鼠标绘制工具</title>
    <style>
        body {
            font-size: 14px;
            font-family: "微软雅黑";
        }

        .config li {
            padding: 2px;
        }

        .colorShow {
            width: 50px;
            border: 1px solid #3e3e3e;
            display: inline-block;
            height: 20px;
            *display: inline;
            *zoom: 1;
        }
    </style>
</head>
<body>
    <div>
        <ul class="config" id="topColorSet">
            <li>
                <label>边线颜色: </label><div data-name="strokeColor" class="colorShow" style="background-color: red">&nbsp;</div>
            </li>
            <li>
                <label>填充颜色: </label><div data-name="fillColor" class="colorShow" style="background-color: red">&nbsp;</div>
            </li>
        </ul>
        <div style="display: none">
            <div id="infoWindow">
                <ul class="config">
                    <li>
                        选择所属：<select id="mapBelongs"></select>
                        <a href="#" id="btnSignMapBelong">标记</a>
                    </li>
                    <li>
                        <label>边线颜色: </label><div data-name="strokeColor" class="colorShow" style="background-color: red">&nbsp;</div>
                    </li>
                    <li>
                        <label>填充颜色: </label><div data-name="fillColor" class="colorShow" style="background-color: red">&nbsp;</div>
                    </li>
                    <li>
                        <a href="#" id="btnClearArea">清除此区域</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
        <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;"></div>
    </div>
    <div id="result">
        <input type="button" value="获取绘制的覆盖物个数" onclick="alert(overlays.length)" />
        <input type="button" value="获取数据" onclick="getData()" />
    </div>
    <script src="//cdn.lizhanglong.com/js/jquery/1.8.3/jquery.min.js"></script>
    <script src="//cdn.lizhanglong.com/js/colorPicker/jquery.colorpicker.js"></script>
    <script src="//cdn.lizhanglong.com/js/plugins/jquery.cookie.min.js"></script>
    <script>
        $(function () {
            $('#topColorSet .colorShow').colorpicker({
                success: function (obj, color) {
                    obj.css('backgroundColor', color);
                    initDrawOption();
                }
            });


            function initDrawOption() {
                var p = {};
                $('.colorShow').each(function () {
                    var self = $(this), name = self.attr('data-name'), bgColor = self.css('backgroundColor');
                    p[name] = bgColor;
                });
                $.extend(styleOptions, p);
            }

            initDrawOption();
        })
    </script>
    <script type="text/javascript">
        // 百度地图API功能
        var map = new BMap.Map('map');
        var poi = new BMap.Point(116.307852, 40.057031);
        map.centerAndZoom(poi, 16);
        map.enableScrollWheelZoom();



        function init(opt) {
            var ids = opt.mapBelongs || [];
            var idTextKv = {};
            $.each(ids, function (i, item) {
                var label = idTextKv[item.value] = item.label || item.text;
                var option = $('<option/>', {
                    text: item.text,
                    value: item.value
                }).data({
                    label: label,
                    location: item.center
                });
                infoWinDoms.mapBelongs.append(option);
            });
            opt.mapData && $.each(opt.mapData, function (i, item) {
                var mapId = item.mapId;
                var labelText = idTextKv[mapId];
                $.each(item.datas, function (j, item1) {
                    var paths = $.map(item1.paths, function (p, z) {
                        return new BMap.Point(p.lng, p.lat);
                    });
                    var center = item1.center;
                    var option = $.extend(true, {}, styleOptions, item1.opts);
                    var polygon = new BMap.Polygon(paths, option);
                    var point = new BMap.Point(center.lng, center.lat);
                    var marker = new BMap.Marker(point);
                    marker.enableDragging();
                    map.addOverlay(polygon);
                    map.addOverlay(marker);
                    var label = new BMap.Label(labelText, {
                        position: point,
                        offset: new BMap.Size(-5, -19)
                    });
                    marker.setLabel(label);
                    marker.data_label = label;
                    polygon.data_marker = marker;
                    polygon.data_mapId = mapId;
                    overlays.push(polygon);
                    bindEvent(polygon);
                });
            });
        }


        //var contextMenu = new BMap.ContextMenu();
        //contextMenu.addItem(new BMap.MenuItem('移除上一个', function () {
        //    console.log(overlays.length);
        //    var last = overlays.pop();
        //    console.log(overlays.length);
        //    last && map.removeOverlay(last);
        //}));
        //  map.addContextMenu(contextMenu);
        //map.addEventListener('rightclick', function () {
        //    drawingManager.close();
        //});
        var overlays = [];

        var infoWinDoms = {
            dialog: $('#infoWindow'),
            mapBelongs: $('#mapBelongs'),
            btnSignMap: $('#btnSignMapBelong'),
            btnClearArea: $('#btnClearArea')
        };
        infoWinDoms.dialog.on('init', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            infoWinDoms.mapBelongs.val(overlay.data_mapId || '');
            if (overlay) {
                infoWinDoms.dialog.find('.colorShow').each(function () {
                    var self = $(this), name = self.attr('data-name'), bgColor;
                    switch (name) {
                        case 'strokeColor':
                            bgColor = overlay.getStrokeColor();
                            break;
                        case 'fillColor':
                            bgColor = overlay.getFillColor();
                            break;
                        default:
                            alert('未知：' + name);
                            break;
                    }
                    bgColor && self.css('backgroundColor', bgColor);
                });
            }
        });

        infoWinDoms.btnSignMap.on('click', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            if (overlay) {
                var opt = infoWinDoms.mapBelongs.find('option:selected');
                var loc = opt.data('location');
                var labelText = opt.data('label') || opt.text();
                if (loc) {
                    loc = new BMap.Point(loc.lng, loc.lat);
                } else {
                    var bound = overlay.getBounds();
                    var center = bound.getCenter();
                    loc = center;
                }
                var marker = overlay.data_marker;
                marker && map.removeOverlay(marker);

                marker = new BMap.Marker(loc);
                marker.enableDragging();
                map.addOverlay(marker);
                var label = new BMap.Label(labelText, {
                    position: loc,
                    offset: new BMap.Size(-5, -19)
                });
                marker.setLabel(label);
                marker.data_label = label;
                overlay.data_marker = marker;
                overlay.data_mapId = opt.val();
            }
            map.closeInfoWindow();

        });
        infoWinDoms.btnClearArea.on('click', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            if (overlay) {
                map.removeOverlay(overlay);
                var index = $.inArray(overlay, overlays);
                if (index != -1) {
                    var marker = overlay.data_marker;
                    marker && map.removeOverlay(marker);
                    overlays.splice(index, 1);
                }
            }
            map.closeInfoWindow();
        });
        infoWinDoms.dialog.find('.colorShow').colorpicker({
            success: function (obj, color) {
                obj.css('backgroundColor', color);
                var name = obj.attr('data-name');
                var overlay = infoWinDoms.dialog.data('overlay');
                if (overlay) {
                    switch (name) {
                        case 'strokeColor':
                            overlay.setStrokeColor(color);
                            break;
                        case 'fillColor':
                            overlay.setFillColor(color);
                            break;
                        default:
                            alert('未知：' + name);
                            break;
                    }
                }
            }
        });

        var infoWindowOption = {
            title: '设置'
        };
        var infoWindow = new BMap.InfoWindow(infoWinDoms.dialog.get(0), infoWindowOption);
        infoWindow.addEventListener('open', function () {
            infoWinDoms.dialog.triggerHandler('init');
        });
        var styleOptions = {
            strokeColor: "red",    //边线颜色。
            fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3,       //边线的宽度，以像素为单位。
            strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
        };
        //实例化鼠标绘制工具
        var drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
                drawingModes: [
                    BMAP_DRAWING_POLYGON,
                    BMAP_DRAWING_RECTANGLE
                ]
            },
            circleOptions: styleOptions, //圆的样式
            polylineOptions: styleOptions, //线的样式
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions //矩形的样式
        });
        //添加鼠标绘制工具监听事件，用于获取绘制结果
        // drawingManager.addEventListener('overlaycomplete', overlaycomplete);
        var MinCircleRadius = 20;/*画圆的最小半径，防止误点地图*/
        var MinDrawArea = 100;/*多边形最小面积（平方米）*/
        drawingManager.addEventListener('circlecomplete', function (overlay) {
            if (overlay.getRadius() >= MinCircleRadius) {
                bindEvent(overlay);
                drawingManager.close();
                overlays.push(overlay);
            } else {
                map.removeOverlay(overlay);
            }
        });
        drawingManager.addEventListener('rectanglecomplete', function (overlay) {
            var ply = new BMap.Polygon(overlay.getPath());
            var area = BMapLib.GeoUtils.getPolygonArea(ply);
            if (area >= MinDrawArea) {
                bindEvent(overlay);
                drawingManager.close();
                return overlays.push(overlay);
            }
            map.removeOverlay(overlay);
        });
        drawingManager.addEventListener('polygoncomplete', function (overlay) {
            if (overlay.getPath().length >= 3) {
                var ply = new BMap.Polygon(overlay.getPath());
                var area = BMapLib.GeoUtils.getPolygonArea(ply);
                if (area >= MinDrawArea) {
                    drawingManager.close();
                    bindEvent(overlay);
                    return overlays.push(overlay);
                }
            } else {
                alert('最少三个点');
            }
            map.removeOverlay(overlay);
        });

        function bindEvent(overlay) {
            overlay.addEventListener('dblclick', function (ev) {
                alert(ev.type);

            });
            overlay.addEventListener('rightclick', function (ev) {
                infoWinDoms.dialog.data('overlay', overlay);
                map.openInfoWindow(infoWindow, ev.point);
            });
        }
        function clearAll() {
            for (var i = 0; i < overlays.length; i++) {
                map.removeOverlay(overlays[i]);
            }
            overlays.length = 0;
        }

        function getData() {
            var data = {};
            $.each(overlays, function (i, overlay) {
                var mapId = overlay.data_mapId;
                if (!mapId) {
                    return;
                }
                var d = data[mapId] || (data[mapId] = []);
                var marker = overlay.data_marker;
                var paths = overlay.getPath(),
                    opts = {},
                    center = marker.getPosition();
                opts['fillColor'] = overlay.getFillColor();
                opts['strokeColor'] = overlay.getStrokeColor();
                d.push({
                    paths: paths,
                    center: center,
                    opts: opts
                });
            });
            var arr = [];
            $.each(data, function (k, v) {
                arr.push({ mapId: k, datas: v });
            });
            console.log(JSON.stringify(arr));
            $.cookie('saveData', JSON.stringify(arr), { path: '' });
            return arr;
        }








        /**
 * 计算一个点是否在多边形里
 * @param {Object} pt 标注点
 * @param {Object} poly 多边形数组
 */
        function isInsidePolygon(pt, poly) {
            for (var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
                ((poly[i].lat <= pt.lat && pt.lat < poly[j].lat) || (poly[j].lat <= pt.lat && pt.lat < poly[i].lat)) &&
                    (pt.lng < (poly[j].lng - poly[i].lng) * (pt.lat - poly[i].lat) / (poly[j].lat - poly[i].lat) + poly[i].lng) &&
                    (c = !c);
            return c;
        }
    </script>

    <script>
        var savedData = $.cookie('saveData');
        var initOpts = {};
        initOpts.mapBelongs = [
                {
                    text: '大厨房',
                    value: '001',
                    label: '大厨房(001)'
                },
                  {
                      text: '0271',
                      value: '0271',
                      label: '坂田(0271)'
                  },
                  {
                      text: '4862',
                      value: '4862',
                      label: '布吉(4862)'
                  }
        ];
        if (savedData) {
            initOpts.mapData = JSON.parse(savedData);
        }
        init(initOpts);
    </script>
</body>
</html>
